package utils;

import cn.hutool.json.JSONUtil;
import context.WxContext;
import entity.pojo.TokenInfo;
import entity.pojo.WxUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
@RequiredArgsConstructor
@Slf4j
public class WxUtil {
    private final RestTemplate restTemplate;

    public WxUser getUserInfo(String code) {
        String tokenUrl = WxContext.spliceTokenUrl(code);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(tokenUrl, String.class);

        String responseResult = "";
        if (responseEntity.getStatusCode().value() == 200) {
            responseResult = responseEntity.getBody();
        }

        log.info("获取到accessToken的返回结果：{}", responseResult);

        //获取token
        TokenInfo tokenInfo = JSONUtil.toBean(responseResult, TokenInfo.class);

        //获取用户信息
        String userInfoUrl = WxContext.spliceGetUserInfoUrl(tokenInfo);

        ResponseEntity<String> userInfoResponseEntity = restTemplate.getForEntity(userInfoUrl, String.class);
        if (userInfoResponseEntity.getStatusCode().value() == 200) {
            responseResult = userInfoResponseEntity.getBody();
        }

        log.info("获取个人信息返回：{}", responseResult);

        return JSONUtil.toBean(responseResult, WxUser.class);
    }
}
